package com.team.panicgame.models.vudduu;

import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.team.panicgame.GameConstants;

public class VudduuPlayer {
	public static enum PLAYER_STATE {
		STILL, RUN, JUMP
	}
	public static final float WIDTH = 1;
	public static final float HEIGHT = 2;
	private Vector2 position;
	private float destinationX;
	private float accelerationY;
	private Rectangle shape;
	
	public PLAYER_STATE state = PLAYER_STATE.STILL;
	
	public VudduuPlayer(VudduuWorld world, float x) {
		world.setPlayer(this);
		position = world.coordinatePlayer();
		destinationX = position.x;
		accelerationY = 0;
		getShape();
	}
	
	public Rectangle getShape() {
		float msize = VudduuWorld.MAP_CELL_SIZE;
		shape = new Rectangle(position.x*msize, position.y*msize, WIDTH*msize, HEIGHT*msize);
		return shape;
	}
	
	public Vector2 getPosition() {
		return position.cpy();
	}

	public void update(VudduuWorld world, float delta) {
		Vector2 dir = new Vector2(destinationX - position.x, accelerationY);
		Vector2 nextPos = position.cpy().add( dir.mul(delta*2) );
		if(isFalling()) {
			if(!isValidPosition(nextPos, world)) {
				accelerationY = 0;
				state = PLAYER_STATE.RUN;
				dir = new Vector2(destinationX - position.x, accelerationY);
				nextPos = position.cpy().add( dir.mul(delta*2) );
			}
		}
		if(isValidPosition(nextPos, world)) {
			position = nextPos;
		}
		
		if(state != PLAYER_STATE.JUMP) {
			if(dir.x > 0.1f) {
				state = PLAYER_STATE.RUN;
			}
			else {
				state = PLAYER_STATE.STILL;
			}
		}
		else {
			accelerationY -= GameConstants.GRAVITY * delta;
		}
	}
	
	public boolean isValidPosition(Vector2 nextPos, VudduuWorld world) {
		int M[][] = world.map;
		if(M[(int)nextPos.x][(int)nextPos.y] == 1) {
			return false;
		}
		if(isFalling() && M[(int)(nextPos.x+WIDTH)][(int)nextPos.y] == 1) {
			return false;
		}
		return true;
	}
	
	public void increaseX(VudduuWorld world, float incX){
		if(incX > 0)
			destinationX = (float) Math.floor( position.x + 1.5f );
		if(incX < 0)
			destinationX = (float) Math.floor( position.x - 0.5f );
		Vector2 nextPos = new Vector2(destinationX, position.y);
		if(!isValidPosition(nextPos, world)) {
			destinationX = position.x;
		}
	}
	
	public void jump() {
		if(state != PLAYER_STATE.JUMP) {
			accelerationY = 5;
			state = PLAYER_STATE.JUMP;
		}
	}

	public boolean isFalling() {
		if(state == PLAYER_STATE.JUMP) {
			if(accelerationY < 0.0) {
				return true;
			}
		}
		return false;
	}
}
